import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:flutter_app/model/song_model.dart';
import 'package:flutter_app/util/show.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';

import 'state.dart';

class SongsLogic extends GetxController {
  int page = 1;
  int limit = 10;
  bool error = false;
  bool hasMore = true;
  bool loading = true;
  String errorMsg = '';
  EasyRefreshController controller;

  final state = SongsState();
  List<SongItem> songList = SongList([]).list;
  RxInt count = 0.obs;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    count++;
    controller = EasyRefreshController();
  }

  ///条目点击
  void show(msg) {
    showToast(msg);
  }

  ///下拉刷新
  Future onRefresh() async {
    if (error) {
      error = false;
    }
    page = 1;
    await getData();
    controller.resetLoadState();
  }

  ///上拉加载
  Future onLoad() async {
    print('加载更多');
    if (hasMore) {
      await getData(push: false);
    }
    controller.finishLoad(noMore: !hasMore);
    update();
  }

  ///获取数据
  Future getData({bool push = true}) async {
    try {
      String data = await rootBundle.loadString("assets/data/song.json");
      Map<String, dynamic> result = jsonDecode(data);
      //将数据转为实体类
      SongList songListModel = SongList.fromJson(result['data']);
      hasMore = page * limit < result['total'];
      page++;
      if (push) {
        songList = songListModel.list;
      } else {
        songList.addAll(songListModel.list);
      }
    } catch (e) {
      error = true;
      errorMsg = e.toString();
    } finally {
      loading = false;
    }
    print('数据${songList.length}');
  }
}
